package twoPointers;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//https://leetcode.cn/problems/4sum/
public class l_18 {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        int n = nums.length;
        Arrays.sort(nums);
        List<List<Integer>> ans = new ArrayList<>();
        //枚举两个数, 剩下两个数用双指针找, 就是在三数之和的基础上再加一个循环
        for(int i = 0; (i < n - 3); ++i) {
            if(i > 0 && nums[i] == nums[i - 1]) continue; //去重
            for(int j = i + 1; (j < n - 2); ++j) {
                if(j > i + 1 && nums[j] == nums[j - 1]) continue; //去重
                int left = j + 1, right = n - 1;
                while(left < right) {
                    if(left > j + 1 && nums[left] == nums[left - 1]) ++left; //去重
                    else if(right < n - 1 && nums[right] == nums[right + 1]) --right; //去重
                    else {
                        //此题会爆int
                        long sum = (long) nums[left] + nums[right];
                        long tar = (long) target - nums[i] - nums[j];
                        if(sum == tar) {
                            ans.add(List.of(nums[i], nums[j], nums[left], nums[right]));
                            ++left;
                            --right;
                        } else if(sum > tar) --right;
                        else ++left;
                    }
                }
            }
        }
        return ans;
    }
}
